$(function(){
	var orderId = wsCommon.getUrlParam('orderId');
	var uploader;

	var comment = {
		getData: function() {
			$('[data-role="orderId"]').html(orderId).attr('href', './member-orderdetail.html?orderId=' + orderId);
			$.ajax({
                url: wsCommon.host + '/api/memberComments/commentSavePre',
                dataType: wsCommon.jsonType,
				data: {
					orderId: orderId
				},
                success: function(res) {
                    if(res.code == 1) {
						if(!res.result) {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
							return;
                        }

						// 快递员信息
						var courier = res.data.courier;
						if(courier) {
							$('[data-role="courier-img"]').html('<img src="'+courier.headPicUrl+'" alt="'+courier.name+'">');
							$('[data-role="courier-info"]').append('<div class="s-info">'+courier.name+' '+courier.mobile+'</div><div class="s-info">'+courier.area+'</div>');
						} else {
							$('[data-role="courier-img"]').html('<img src="images/bg-who1.png" alt="">');
							$('[data-role="courier-info"]').append('<div class="s-info">配送小哥需要您的鼓励</div>');
						}

						// 是否已经评价
						var commentCourier = res.data.commentCourier;
						if(commentCourier) {
							$('[data-role="serve-tips"]').hide();
							$('[data-role="goos-serve"]').hide();
							$('[data-role="server-bz"]').addClass('active').find('.star-info').html(commentCourier.pointPacking+'分').addClass('highlight');
							$('[data-role="server-bz"]').find('.star' + commentCourier.pointPacking).addClass('active');
							$('[data-role="server-sd"]').addClass('active').find('.star-info').html(commentCourier.pointPacking+'分').addClass('highlight');
							$('[data-role="server-sd"]').find('.star' + commentCourier.pointSpeed).addClass('active');
							$('[data-role="server-td"]').addClass('active').find('.star-info').html(commentCourier.pointPacking+'分').addClass('highlight');
							$('[data-role="server-td"]').find('.star' + commentCourier.pointAttitude).addClass('active');
						} else {
							$('[data-role="server-submit"]').show();
						}

						var list = res.data.pager.list;
						var tpl = '';
						$.each(list, function(index, item) {
							if(index == 0) {
								$('[data-role="diverTime"]').html(item.buyTimeStr);
							}
							tpl += '<div class="f-item f-goods">\
			                            <div class="fi-info">\
			                                <div class="comment-goods">\
			                                    <div class="p-img"><a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank"><img src="'+item.goodsPic+'"></a></div>\
			                                    <div class="p-name"><a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank">'+item.goodsName+'</a></div>\
			                                    <div class="p-price"><strong>¥'+item.productPrice+'</strong></div>\
			                                </div>\
			                            </div>\
			                            <div class="fi-operate">\
			                                <div class="fop-item fop-star z-tip-warn">\
			                                    <div class="fop-label">商品满意度</div>\
			                                    <div class="fop-main">\
			                                        <span class="commstar">\
			                                            <span class="star star1"><i class="face"></i></span>\
			                                            <span class="star star2"><i class="face"></i></span>\
			                                            <span class="star star3"><i class="face"></i></span>\
			                                            <span class="star star4"><i class="face"></i></span>\
			                                            <span class="star star5 active"><i class="face"></i></span>\
			                                            <span class="star-info highlight" data-goodsId="'+item.goodsId+'" data-productId="'+item.productId+'" data-orderId="'+orderId+'">5分</span>\
			                                        </span>\
			                                    </div>\
			                                    <div class="fop-tip"><i class="tip-icon"></i><em class="tip-text"></em></div>\
			                                	<div class="fi-tip"><i class="tip-icon"></i><em class="tip-text">请至少填写一件商品的评价</em></div>\
			                                </div>\
			                                <div class="fop-item ">\
			                                    <div class="fop-label">评价晒单</div>\
			                                    <div class="fop-main">\
			                                        <div class="f-textarea">\
			                                            <textarea name="" class="experience" placeholder="商品是否给力？快分享你的购买心得吧~"></textarea>\
			                                            <div class="textarea-ext"><em class="textarea-num"><b>0</b> / 500</em\></div>\
			                                        </div>\
			                                        <div class="m-imgshow f-imgshow">\
			                                            <div class="thumbnail-list" style="position: relative;">\
															<div id="fileList'+index+'" class="uploader-list">\
															</div>\
			                                                <span class="btn-upload" id="upload'+index+'" style="position: relative; z-index: 0;"></span>\
			                                                <span class="upload-num">共<em data-role="curnum">0</em>张,还能上传<em data-role="totalnum">10</em>张</span>\
			                                            </div>\
	                                        </div>\
	                                    </div>\
	                                    <div class="fop-tip"><i class="tip-icon"></i><em class="tip-text"></em></div>\
	                                </div>\
	                            </div>\
	                        </div>';
						})
						$('.form-part1').append(tpl);

						$('.experience').charcount({
						    position: 'none'
						}).bind('update', function(evt, length, remaining) {
						    $(this).next('.textarea-ext').find('b').text(length);
						});

						$.each(list, function(index, item) {
							comment.uploadPic(index);
						})
                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
				}
            })
		},
		// 服务评价
		serverEvaluate: function() {
			$('[data-role="server-evaluate"]').on('click', function() {
				var $this = $(this);
				var bz = $('[data-serve="bz"]').html().substring(0, 1);
				var sd = $('[data-serve="sd"]').html().substring(0, 1);
				var td = $('[data-serve="td"]').html().substring(0, 1);
				if(bz == 0 || sd == 0 || td == 0) {
					iosOverlay({
                        text: "请填写完整！",
                        duration: 1500
                    });
				} else {
					$.ajax({
						url: wsCommon.host + '/api/memberComments/commentCourierSave',
						dataType: wsCommon.jsonType,
						data: {
							orderId: orderId,
							pointPacking: bz,
							pointSpeed: sd,
							pointAttitude: td
						},
						success: function(res) {
							if(res.code == 1) {
								iosOverlay({
									text: '配送服务评价成功！',
									duration: 1000
								});
								$this.closest('.f-btnbox').hide();
								$('[data-role="server-bz"]').addClass('active')
								$('[data-role="server-sd"]').addClass('active')
								$('[data-role="server-td"]').addClass('active')
							} else {
								iosOverlay({
									text: res.reason,
									duration: 1000
								});
							}
						},
						error: function(e) {
						}
					})
				}
			})
		},
		// 商品评价
		goodsEvaluate: function() {
			$('[data-role="goods-evaluate"]').on('click', function() {
				var hiddenName;
				if($('#check1').prop('checked')) {
					hiddenName = 'YES';
				} else {
					hiddenName = 'NO';
				}

				var canSubmit = false;
				$.each($('.experience'), function(index, item) {
					if($(item).val().trim() != '') {
						canSubmit = true;
					}
				})

				if(canSubmit) {
					var submitArr = [];
					$.each($('.f-goods'), function(index, item) {
						var $item = $(item).find('.star-info');
						if($(item).find('.experience').val().trim() != '') {
							var obj = {};
							obj.goodsId = $item.attr('data-goodsId');
							obj.productId = $item.attr('data-productId');
							obj.orderId = $item.attr('data-orderId');
							obj.point = $item.html().substring(0, 1);
							obj.comment = $(item).find('.experience').val().trim();
							obj.hiddenName = hiddenName;
							var picArr = [];

							$.each($(item).find('.uploader-list').find('.file-item'), function(indexDir, itemDir) {
								picArr.push($(itemDir).attr('data-url'))
							})
							obj.showPicUrl = picArr.join(',');
							submitArr.push(obj)
						}
					})

					$.ajax({
					    url: wsCommon.host + '/api/memberComments/commentGoodsSave',
					    dataType: wsCommon.jsonType,
						data: {
							commentsJson: JSON.stringify(submitArr)
						},
					    success: function(res) {
					        if(res.code == 1) {
					            if(!res.result) {
					                wsCommon.setCookie('go_back_link', window.location.href);
					                window.location.href = './passport-login.html';
					                return;
					            }

								window.location.href = './comment_done.html?orderId=' + orderId;
					        } else {
					            iosOverlay({
					                text: res.reason,
					                duration: 1000
					            });
					        }
					    },
					    error: function(e) {
					    }
					})
				} else {
					iosOverlay({
						text: '请至少填写一件商品的评价!',
						duration: 1000
					});
				}
			})
		},
		delUploadPic: function() {
			$(document).on('click', '.imgdel', function() {
				if(!$(this).closest('.file-item').find('.imgtips').length) {
					uploader.removeFile( $(this).attr('data-imgid') , true);
					var $curnum = $(this).closest('.thumbnail-list').find('[data-role="curnum"]');
					$curnum.text(Number($curnum.text()) - 1);
					var $totalnum = $(this).closest('.thumbnail-list').find('[data-role="totalnum"]');
					$totalnum.text(Number($totalnum.text()) + 1);
				}
				$(this).closest('.file-item ').remove();
			})
		},
		// 图片上传
		uploadPic: function(index) {

			// 初始化Web Uploader
			uploader = WebUploader.create({

			    // 选完文件后，是否自动上传。
			    auto: true,
			    // swf文件路径
			    swf: './js/Uploader.swf',
				method: 'POST',
				fileVal: 'Filedata',
			    // 文件接收服务端。
			    server: wsCommon.host + '/api/memberComments/upload',

			    // 选择文件的按钮。可选。
			    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
			    pick: '#upload' + index,
				duplicate: true,
				fileNumLimit: 10,

			    // 只允许选择图片文件。
			    accept: {
			        title: 'Images',
			        extensions: 'gif,jpg,jpeg,bmp,png',
			        mimeTypes: 'image/jpg,image/jpeg,image/png'
			    }
			});

			// 当有文件添加进来的时候
			uploader.on( 'fileQueued', function( file ) {
			    var $li = $(
			            '<div id="' + file.id + '" class="file-item thumbnail">' +
			                '<img>' +
							'<span class="imgdel">删除</span>' +
			            '</div>'
			            ),
			        $img = $li.find('img');


			    // $list为容器jQuery实例
			    $('#fileList'+index).append( $li );

			    // 创建缩略图
			    // 如果为非图片文件，可以不用调用此方法。
			    // thumbnailWidth x thumbnailHeight 为 100 x 100
			    uploader.makeThumb( file, function( error, src ) {
			        if ( error ) {
			            $img.replaceWith('<span>不能预览</span>');
			            return;
			        }

			        $img.attr( 'src', src );
			    }, 48, 48 );
			});

			// 文件上传成功，给item添加成功class, 用样式标记上传成功。
			uploader.on( 'uploadSuccess', function( file, res ) {
				$('#' + file.id).attr('data-url', res.url);
				$('#' + file.id).find('.imgdel').attr('data-imgid', file.id);
				var $curnum = $('#' + file.id).closest('.thumbnail-list').find('[data-role="curnum"]');
				$curnum.text(Number($curnum.text()) + 1);
				var $totalnum = $('#' + file.id).closest('.thumbnail-list').find('[data-role="totalnum"]');
				$totalnum.text(Number($totalnum.text()) - 1);
			});
			uploader.on('uploadError', function(file, reason){
				$('#' + file.id).append('<span class="imgtips" style="position:absolute;width:100%;height:20px;line-height:20px;text-align:center;top:0;left:0;background-color:#333;color:#f5f5f5;">上传失败</span>')
	        })

			uploader.on('error', function(file, reason){
				if(file == 'Q_EXCEED_NUM_LIMIT') {
					iosOverlay({
						text: '最多可上传10个图片',
						duration: 1000
					});
				}
	        })

		},
		init: function() {
			this.getData();
			this.goodsEvaluate();
			this.serverEvaluate();
			this.delUploadPic();
		}
	}

	comment.init();
})

// <div class="thumbnail-item">\
// 	<img  src="img/hg5.jpg">\
// 	<div class="thumbnail-operate">\
// 		<span class="op-edit"></span>\
// 		<span class="op-delete"></span>\
// 	</div>\
// </div>\
// <div class="fop-item J-mjyx">
// 	<div class="fop-label">买家印象</div>
// 	<div class="fop-main">
// 		<div class="m-tagbox m-multi-tag">
// 			<a href="javascript:void(0)" class="tag-item tag-checked">屏幕大<i class="t-check"></i></a>
// 			<a href="javascript:void(0)" class="tag-item">3D效果好<i class="t-check"></i></a>
// 			<a href="javascript:void(0)" class="tag-item" data-id="9851">一般<i class="t-check"></i></a>
// 			<a href="javascript:void(0)" class="tag-item" data-id="3467">色彩好<i class="t-check"></i></a>
// 			<a href="javascript:void(0)" class="tag-item" data-id="3475">功能齐全<i class="t-check"></i></a>
// 			<a href="javascript:void(0)" class="tag-item" data-id="3478">售后好<i class="t-check"></i></a>
// 			<a href="javascript:void(0)" class="tag-item" data-id="3474">外观漂亮<i class="t-check"></i></a>
// 			<a href="javascript:void(0)" class="tag-item" data-id="3472">边框很窄<i class="t-check"></i></a>
// 			<a href="javascript:void(0)" class="tag-item" data-id="3473">送了底座<i class="t-check"></i></a>
// 		</div>
// 	</div>
// 	<div class="fop-tip"><i class="tip-icon"></i><em class="tip-text"></em></div>
//  </div>
